/**
 * @Title: DJobScheduleHelper.java
 * @Package com.xxl.job.admin.core.thread
 * @author roc
 * @date 2020年9月23日 下午8:47:02
 * @version V1.0
 * @copyright kaver
 */
package com.xxl.job.admin.core.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.dao.XxlJobInfoDao;

/**
 * @ClassName: DJobScheduleHelper
 * @Description: 动态job清理任务
 * @author roc
 * @date 2020年9月23日 下午8:47:02
 * 
 */
public class DJobScheduleHelper {

    private static Logger logger = LoggerFactory.getLogger(DJobScheduleHelper.class);

    private static DJobScheduleHelper instance = new DJobScheduleHelper();

    public static DJobScheduleHelper getInstance() {
        return instance;
    }

    public static final long PRE_READ_MS = 10 * 60 * 1000;

    private Thread scheduleThread;

    private volatile boolean scheduleThreadToStop = false;

    public void start() {
        scheduleThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!scheduleThreadToStop) {
                    try {
                        XxlJobInfoDao dao = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao();
                        dao.clearDJob();
                        Thread.sleep(PRE_READ_MS);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        });
        scheduleThread.start();
    }

    public void toStop() {
        scheduleThreadToStop = true;
        if (scheduleThread.getState() != Thread.State.TERMINATED) {
            // interrupt and wait
            scheduleThread.interrupt();
            try {
                scheduleThread.join();
            } catch (InterruptedException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}
